package cn.nawang.ebeim.persist.utils;

import cn.nawang.ebeim.persist.handler.ResultSetHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: 甘竞存
 * Date: 14-11-10
 * Time: 上午10:19
 * 对操作数据库的封装
 */
public class DBUtils {

    public static void execute(Connection con, String sql, Object[] params) throws SQLException {
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            st = con.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    st.setObject(i + 1, params[i]);
                }
            }
            st.executeUpdate();
        } finally {
            release(con, st, rs);
        }
    }

    public static Object find(Connection con, String sql, Object[] params, ResultSetHandler rsh) throws SQLException {
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            st = con.prepareStatement(sql);
            if(params!=null){
                for (int i = 0; i < params.length; i++) {
                    st.setObject(i + 1, params[i]);
                }
            }
            rs = st.executeQuery();
            // 委托处理器 对结果集进行处理
            return rsh.handler(rs);
        } finally {
            release(con, st, rs);
        }
    }

    private static void release(Connection con, PreparedStatement st, ResultSet rs) {
        try {
            if (con != null) con.close();
            if (st != null) st.close();
            if (rs != null) rs.close();
        } catch (SQLException e) {
        }
    }
}
